import React, { Component } from 'react'
import Header from './componens/Header'
import List from './componens/List'
import Footer from './componens/Footer'

export default class App extends Component {

  // 状态
  state = {
    list: [
      {
        id: 1001,
        text: '吃饭',
        done: true
      },
      {
        id: 1002,
        text: '睡觉',
        done: true
      },
      {
        id: 1003,
        text: '敲代码',
        done: false
      },
    ]
  }

  // 添加一个任务
  addListItem = () => {
    return (e) => {
      const newList = [e, ...this.state.list]
      this.setState({list: newList})
    }
  }

  // 更新一个任务的勾选状态到 state 中
  updateList = (id, done) => {
    const { list } = this.state
    const newList = list.map((item) => {
      if (item.id === id) return {...item, done}
      return item
    })
    this.setState({ list: newList })
  }

  // 子组件传递 id 来删除列表数据
  delList = (id) => {
    const { list } = this.state
    const newList = list.filter(item => item.id !== id)
    this.setState({ list: newList })
  }

  // 根据子组件的全选框勾选状态来确定列表的勾选
  checkAll = (doneAll) => {
    const { list } = this.state
    const newList = list.map(item => {
      return {...item, done: doneAll}
    })
    this.setState({ list: newList })
  }

  // 根据子组件触发删除事件来删除列表
  delListComplete = () => {
    const { list } = this.state
    const newList = list.filter(item => {
      return !item.done
    })
    this.setState({ list: newList })
  }

  render() {
    const { list } = this.state
    return (
      <div className="todo-container">
        <div className="todo-wrap">
          <Header addList={this.addListItem()}/>
          <List list={list} updateList={ this.updateList } delList={this.delList}/>
          <Footer list={list} checkAll={ this.checkAll } delListComplete={ this.delListComplete }/>
        </div>
      </div>
    )
  }
}